package com.timanetworks.rtm.vehicle.status.handler.remind;


import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * 发送邮件服务样板代码，可作为spring容器对象注入使用。
 * 本例使用guice
 * maven：
 *         <dependency>
 *           <groupId>javax.mail</groupId>
 *           <artifactId>mail</artifactId>
 *           <version>1.4.7</version>
 *       </dependency>
 */
public class MailSendService {

    private static final Logger logger = LoggerFactory.getLogger(MailSendService.class);

    @Inject
    @Named("service.mail.server.host")
    private String host;

    @Inject
    @Named("service.mail.user.name")
    private String uname;

    @Inject
    @Named("service.mail.user.password")
    private String password;

    @Inject
    @Named("service.mail.account.from")
    private String from;

    private Session session;

    public void init(){
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");//必须 普通客户端
        properties.setProperty("mail.transport.protocol", "smtp");//必须选择协议
        properties.setProperty("mail.host", host);
        properties.setProperty("mail.debug", "false");

        session = Session.getDefaultInstance(properties);
        logger.info("Mail session has initialize. host = {}", host);
    }

    /**
     * 发送简单文本邮件
     * @param target  收件人
     * @param subject 邮件主题
     * @param content 邮件内容（不包含图片，附件等）
     */
    public void send(String target, String subject, String content){
        if(null == session){
            init();
        }
        Message message = new MimeMessage(session);
        try{
            //发件人
            message.setFrom(new InternetAddress(from));
            //主题
            message.setSubject(subject);
            //收件人
            message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(target));
            //设置抄送自己
            message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(from));
            //邮件内容
            message.setContent(content, "text/html;charset=gbk");

            Transport transport = session.getTransport();
            transport.connect(uname, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.info("Send mail successfully. mail subject = {}, mail receivers = {}", subject, target);
        }catch (Exception e){
            logger.error("Send mail fail. mail subject = {}, mail receivers = {}", subject, target);
            logger.error("", e);
        }
    }

    /**
     * 发送复杂邮件
     * @param target  收件人
     * @param subject 邮件主题
     * @param body 邮件内容关系描述（包含图片，附件等）
     */
    public void send(String target, String subject, MimeMultipart body){
        if(null == session){
            init();
        }
        Message message = new MimeMessage(session);
        try{
            //发件人
            message.setFrom(new InternetAddress(from));
            //主题
            message.setSubject(subject);
            //收件人
            message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(target));
            //设置抄送自己
            message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(from));
            //邮件内容
            message.setContent(body);

            Transport transport = session.getTransport();
            transport.connect(uname, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.info("Send mail successfully. mail subject = {}, mail receivers = {}", subject, target);
        }catch (Exception e){
            logger.error("Send mail fail. mail subject = {}, mail receivers = {}", subject, target);
            logger.error("", e);
        }
    }
}
